package org.apache.lucene.ocean;

import java.util.List;

import org.apache.lucene.analysis.Analyzer;

public class SingleThreadTransaction extends AbstractTransaction {

  public SingleThreadTransaction(Long id, List<Long> documentIds, Snapshot previousSnapshot, Batch batch, TransactionSystem system) throws Exception {
    super(id, documentIds, previousSnapshot, batch, system);
  }

  public CommitResult call() throws Exception {
    if (batch.hasDeletes()) {
      for (Index index : previousSnapshot.getDeleteOnlyIndices()) {
        new DeletesTask(batch.getDeletes(), index).call();
      }
    } else {
      for (Index index : previousSnapshot.getDeleteOnlyIndices()) {
        index.commitNothing(this);
        //new DeletesTask(batch.getDeletes(), index).call();
      }
    }
    WriteableMemoryIndex writeableIndex = (WriteableMemoryIndex) previousSnapshot.getWriteableSnapshot().getIndex();
    if (batch.hasRAMDirectory()) {
      new AddRamIndexDocumentsTask(batch.getRamDirectory(), writeableIndex).call();
    } else if (batch.hasDocuments()) {
      Documents documents = batch.getDocuments();
      Analyzer analyzer = batch.getAnalyzer();
      new AddWriteableMemoryDocumentsTask(documents, analyzer, batch.getDeletes(), writeableIndex).call();
    } else if (batch.hasDeletes()) {
      new DeletesTask(batch.getDeletes(), writeableIndex).call();
    } else {
      writeableIndex.commitNothing(this);
    }
    handleMasterBatch();
    return createCommitResult();
  }
}
